package cn.kz.keepass_android.util;

import java.util.List;

import de.slackspace.openkeepass.KeePassDatabase;
import de.slackspace.openkeepass.domain.Entry;
import de.slackspace.openkeepass.domain.KeePassFile;
import de.slackspace.openkeepass.domain.filter.Filter;
import de.slackspace.openkeepass.domain.filter.ListFilter;

/**
 * Created by kz on 2017/3/8.
 */
public class KeepassUtil {

    public static KeePassFile getDB(String path, String password) {

        System.out.println("getDB:" + path + "\t" + password);
        KeePassFile database = null;
        database = KeePassDatabase.getInstance(path).openDatabase(password);
        return database;
    }


    public static List<Entry> getAll(KeePassFile database) {
        return database.getEntries();
    }

    public static List<Entry> search(KeePassFile database, String args) {
        System.out.println("args:" + args);
        if (args == null || args.length() == 0)
            return database.getEntries();

        List<Entry> entriesByUrl = getEntriesByUrl(database, args, false);
        List<Entry> entriesByTitle = database.getEntriesByTitle(args, false);

        entriesByTitle.addAll(entriesByUrl);
        return entriesByTitle;
    }

    public static List<Entry> getEntriesByUrl(KeePassFile database, final String url, final boolean matchExactly) {
        List<Entry> allEntries = database.getEntries();

        return ListFilter.filter(allEntries, new Filter<Entry>() {

            @Override
            public boolean matches(Entry item) {
                if (matchExactly) {
                    if (item.getUrl() != null && item.getUrl().equalsIgnoreCase(url)) {
                        return true;
                    }
                } else {
                    if (item.getUrl() != null && item.getUrl().toLowerCase().contains(url.toLowerCase())) {
                        return true;
                    }
                }

                return false;
            }

        });
    }
}
